import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'node:path'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { viteExternalsPlugin } from 'vite-plugin-externals'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  return {
    plugins: [
      vue(),
      viteExternalsPlugin({
        'mapbox-gl': 'mapboxgl'
      }),
      AutoImport({
        imports: ['vue', '@vueuse/core'],
        include: [/\.[tj]sx?$/, /\.vue$/, /\.vue\?vue/, /\.md$/],
        dts: 'src/types/auto-imports.d.ts',
        resolvers: [ElementPlusResolver()]
      }),
      Components({
        resolvers: [ElementPlusResolver()],
        dts: 'src/types/components.d.ts'
      })
    ],
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src')
      }
    },
    server: {
      host: true,
      port: 9980
    },
    build: {
      sourcemap: false,
      minify: 'esbuild',
      target: 'esnext',
      cssTarget: 'chrome80',
      rollupOptions: {
        // 关闭除屑优化，防止删除重要代码，导致打包后功能出现异常
        // treeshake: false,
        output: {
          // 将大块分解成更小的块
          manualChunks(id) {
            if (id.includes('node_modules')) {
              const moduleName = id.toString().split('node_modules/')[1].split('/')[0].toString()
              if (moduleName.includes('d3')) return 'D3'
              if (moduleName.includes('lodash')) return 'lodash'
              if (moduleName.includes('vue')) return 'vue'
              return moduleName
            }
          },
          // 静态资源分类打包
          // assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
          chunkFileNames: (chunkInfo) => {
            const facadeModuleId = chunkInfo.facadeModuleId ? chunkInfo.facadeModuleId.split('/') : []
            const fileName = facadeModuleId[facadeModuleId.length - 2] || '[name]'
            return `js/${fileName}/[name].[hash].js`
          }
        }
      },
      // 启用/禁用 gzip 压缩大小报告
      reportCompressedSize: false,
      // 提高超大静态资源警告大小
      chunkSizeWarningLimit: 2000
    },
    esbuild: {
      //清除全局的console.log和debug
      drop: mode === 'prod' ? ['console', 'debugger'] : []
    },
    css: {
      preprocessorOptions: {
        scss: {
          api: 'modern'
        }
      }
    }
  }
})
